package com.colbert.jknife.handler;

import com.colbert.jknife.annotation.AnnotationType;
import com.colbert.jknife.annotation.BindView;
import com.colbert.jknife.model.Constant;
import com.colbert.jknife.model.FieldCodeSet;
import com.colbert.jknife.model.ICodeSetManager;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.TypeName;

import javax.lang.model.element.Element;
import javax.lang.model.element.VariableElement;

@AnnotationType(BindView.class)
public class BindViewAnnotationHandler extends BaseAnnotationHandler {

    @Override
    public boolean checkElement(Element element) {
        if(!(element instanceof VariableElement)) {
            error(String.format("@%s can only be used in fields.", BindView.class.getSimpleName()), element);
            return false;
        }
        return true;
    }

    @Override
    public void makeFieldCodeSet(Element element, ICodeSetManager codeSetManager) throws Exception {
        BindView annotation = element.getAnnotation(BindView.class);
        String className = getClassName(element);
        FieldCodeSet fieldCodeSet = codeSetManager.getOrCreateFieldCodeSet(className, annotation.value());
        checkFieldBlock(fieldCodeSet, annotation.value());
        fieldCodeSet.addMethodCodeBlock(CodeBlock.of("$L.$L = ($T) $L;", Constant.TARGET, element.getSimpleName().toString(), TypeName.get(element.asType()), Constant.VIEW_LITERAL));
    }
}
